/*
 * @Description:
 * @Author: qingyang
 * @Date: 2023-06-05 16:00:57
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-06 15:04:38
 */
import { onMounted, ref } from 'vue';
import { systemNotifyList, systemNotifyDetail } from '@/apis/workbench/index';
import { SystemNotifyListResult } from '@/apis/workbench/model/workbenchModel';
import { moduleTypeEnum } from '@/constants/enum';
import { getReleaseInfoDetail } from '@/apis/system/information';

export const useNotice = () => {
  const maxPage = ref(0); //最大页数
  const scrollRef = ref();
  const currentPage = ref(1);
  const hasMore = ref(true); // 触发加载更多
  const loading = ref(false);

  // 详情
  const editorRef = ref();
  const dialogVisible = ref(false);

  const noticeList = ref<SystemNotifyListResult[]>([]);
  const loadList = async (isLoadMore?: boolean) => {
    const params = {
      current: currentPage.value,
      size: 4,
      module: moduleTypeEnum.SYSTEM_NOTICE
    };
    const data = await systemNotifyList(params);
    maxPage.value = data.pages;
    if (isLoadMore) {
      noticeList.value = [...noticeList.value, ...data.records];
      loading.value = false;
      scrollRef.value?.update();
    } else {
      noticeList.value = data.records;
      scrollRef.value?.setScrollTop(0);
    }
  };

  onMounted(() => {
    loadList();
  });
  const loadMore = () => {
    if (!hasMore.value) return;
    currentPage.value++;
    loading.value = true;
    if (currentPage.value > maxPage.value) {
      loading.value = false;
      hasMore.value = false;
    } else {
      hasMore.value = true;
      loadList(true);
    }
  };
  const scroll = (val: any) => {
    const scrollWrap = scrollRef.value?.wrapRef;
    if (scrollWrap && scrollWrap.scrollHeight - val.scrollTop <= scrollWrap.clientHeight + 10) {
      // 滚动到底了
      loadMore();
    }
  };
  const dialogMain = ref<any>({});
  const toDialog = (item: SystemNotifyListResult) => {
    if (item.sendType == 'LINK_URL') {
      window.open(item.content);
    } else {
      getReleaseInfoDetail(item.id).then(res => {
        if (item.sendType == 'TEXT_FILE') {
          dialogMain.value = res;
          dialogVisible.value = true;
        } else {
          window.location.href = res.files[0].fileUrl;
        }
      });
    }
  };

  return {
    noticeList,
    scroll,
    scrollRef,
    hasMore,
    loading,
    dialogMain,
    dialogVisible,
    editorRef,
    toDialog
  };
};
